<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="套餐名称" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入套餐名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商家名称" prop="shopName"
                    v-if="(userStore.shopId == null && route.query.packageableType == null) || userStore.userType === '0'">
        <el-input
            v-model="queryParams.shopName"
            placeholder="请输入商家名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="价格区间">
        <el-row>
          <el-col :span="11">
            <el-input-number v-model="queryParams.minimumPrice" :controls="false"
                             placeholder="最小价格"></el-input-number>
          </el-col>
          <el-col :span="2">-</el-col>
          <el-col :span="11">
            <el-input-number v-model="queryParams.maximumPrice" :controls="false"
                             placeholder="最大价格"></el-input-number>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="套餐类型" prop="packageableType"
                    v-if="(userStore.shopId == null && route.query.packageableType == null) || (userStore.userType === '0' && route.query.packageableType == null)">
        <el-select v-model="queryParams.packageableType" placeholder="请选择套餐类型" clearable>
          <el-option
              v-for="dict in package_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="userStore.shopId != null ||  (route.query.packageableType === 'Play' && route.query.playType === '1' && route.query.isPush === 'N')">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:package:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5" v-if="userStore.shopId != null ||  route.query.packageableType === 'Play' && route.query.playType === '1' && route.query.isPush === 'N'">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:package:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:package:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch"
                     @queryTable="getList(route.params && route.params.id)"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="packageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="套餐名称" align="center" prop="name"/>
      <el-table-column label="套餐价格" width="100" align="center" prop="packagePrice"/>
      <el-table-column label="活动报名时间" align="center" prop="contractStartTime" width="300" v-if="route.query.packageableType === 'Play'">
        <template #default="scope">
          <span>{{
              scope.row.purchaseStartTime
            }}-{{ scope.row.purchaseEndTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="套餐排序" width="100" align="center" prop="sort"/>
      <el-table-column label="已售数量" width="100" align="center" prop="sold"/>
      <el-table-column label="类型" width="100" align="center" prop="packageableType">
        <template #default="scope">
          <dict-tag :options="package_type" :value="scope.row.packageableType"/>
        </template>
      </el-table-column>
      <el-table-column  :label="(route.query.packageableType === 'Play')? '套餐人数' : '库存'" width="100" align="center" prop="store"/>
      <el-table-column label="操作" align="center"  width="300"  class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row, scope.index)"
                     v-hasPermi="['system:package:query']">套餐详情
          </el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-if="userStore.shopId != null ||  (route.query.packageableType === 'Play' && route.query.playType === '1' && route.query.isPush === 'N')"
                     v-hasPermi="['system:package:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-if="userStore.shopId != null ||  (route.query.packageableType === 'Play' && route.query.playType === '1' && route.query.isPush === 'N')"
                     v-hasPermi="['system:package:remove']">删除
          </el-button>
<!--          <el-button link type="primary" icon="Money" @click="handleEvaluation(scope.row)">评价列表</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList(route.params && route.params.id)"
    />

    <!-- 添加或修改团购套餐对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="packageRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="套餐名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入套餐名称" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="route.query.packageableType === 'Business' || userStore.userType === '2'">
            <el-form-item label="有效时间" prop="effectiveTime">
              <el-select v-model="form.effectiveTime" placeholder="请选择有效期" clearable>
                <el-option
                    v-for="dict in effective_time"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="主图" prop="mainPic">
              <image-upload v-model="form.mainPic" :limit="1"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详情图" prop="detailPic">
              <image-upload v-model="form.detailPic"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="套餐价格" prop="packagePrice">
              <el-input-number v-model="form.packagePrice" :controls="false" placeholder="请输入套餐价格" min="0.01"
                               :precision="2"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="原价" prop="price"
                          v-if="route.query.packageableType === 'Business' || userStore.userType === '2'">
              <el-input-number v-model="form.price" :controls="false" placeholder="请输入原价" min="0.01"
                               :precision="2"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="预约信息" prop="reserveInfo" v-if="route.query.packageableType === 'Business' || userStore.userType === '2'">
              <el-select v-model="form.reserveInfo" placeholder="请选择预约信息" clearable>
                <el-option
                    v-for="dict in package_reserve_info"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="route.query.packageableType === 'Business' || userStore.userType === '2'">
            <el-form-item label="使用时间" prop="serviceTime">
              <el-select v-model="form.serviceTime" placeholder="请选择使用时间" clearable>
                <el-option
                    v-for="dict in package_service_time"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
         <el-col :span="12">
           <el-form-item label="适用人数" prop="personNum">
             <el-input-number v-model="form.personNum" :controls="false" placeholder="请输适用人数" min="1" max="999"/>
           </el-form-item>
         </el-col>
          <el-col :span="12">
            <el-form-item :label="(route.query.packageableType === 'Play') ? '套餐人数' :'库存'" prop="store">
              <el-input-number v-model="form.store" :controls="false" placeholder="请输入" min="0"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="route.query.packageableType === 'Play'">
            <el-form-item label="报名时间" prop="purchaseStartTime">
              <el-date-picker
                  clearable
                  v-model="purchaseStartTimeRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD HH:mm"
                  @change="handlePurchaseStartTimeRangeChange"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="限购次数" prop="limitTimes"
                          v-if="route.query.packageableType === 'Business' || userStore.userType === '2'">
              <el-input-number v-model="form.limitTimes" :controls="false" placeholder="请输入限购次数"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述">
              <editor v-model="form.desc" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="套餐详情" v-model="viewOpen" width="1000px" append-to-body>
      <el-form ref="packageRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="名称:" prop="name">
              {{ form.name }}
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="route.query.packageableType === 'Business' || userStore.userType === '2'">
            <el-form-item label="有效时间" prop="effectiveTime">
              {{form.effectiveTimeLabel}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.packageableType === 'Business'">
          <el-col :span="12">
            <el-form-item label="主图" prop="mainPic">
              <image-preview :src="form.mainPic" :width="150" :height="150"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详情图" prop="detailPic">
              <image-preview v-if="fileList.length === 0" :src="form.detailPic" :width="150" :height="150"/>
              <image-preview v-if="fileList.length > 0" :src-list="fileList" :width="150" :height="150"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="原价" prop="price" v-if="form.packageableType === 'Business'">
              {{ form.price }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="套餐价格" prop="packagePrice">
              {{ form.packagePrice }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="预约信息" prop="reserveInfo">
              {{ form.reserveInfoLabel }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用时间" prop="serviceTime" v-if="route.query.packageableType === 'Business' || userStore.userType === '2'">
              {{ form.serviceTimeLabel }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="form.packageableType === 'Business'">
            <el-form-item label="适用人数" prop="personNum">
              {{form.personNum}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="(form.packageableType === 'Play') ? '套餐人数' :'库存'" prop="store">
              {{ form.store }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="form.packageableType === 'Play'">
            <el-form-item label="报名开始" prop="purchaseStartTime">
              {{ form.purchaseStartTime }}
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.packageableType === 'Play'">
            <el-form-item label="报名结束" prop="purchaseEndTime">
              {{ form.purchaseEndTime }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="限购次数" prop="limitTimes" v-if="form.packageableType === 'Business'">
              {{ form.limitTimes }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述">
              <div v-html="form.desc"></div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="购买须知" v-if="form.packageableType === 'Business'">
              <div v-html="form.purchaseNotes"></div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PackageList">
import {listPackage, getPackage, delPackage, addPackage, updatePackage} from "@/api/system/package";

const route = useRoute();
const {proxy} = getCurrentInstance();
const {package_type,effective_time,package_service_time,package_reserve_info} = proxy.useDict('package_type','effective_time','package_service_time','package_reserve_info');
import {watch, onBeforeUnmount, ref} from "vue";
import useUserStore from '@/store/modules/user'
import router from "@/router";

const userStore = useUserStore()
const packageList = ref([]);
const open = ref(false);
const viewOpen = ref(false);
const fileList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const purchaseStartTimeRange = ref([]);
const personNum = ref(0);
const tablePersonNum = ref(0);
const playEndTime = ref('');
const playSignEnd = ref('');
const playType = ref('')
const editPersonNum = ref(0);
const vueIndex = ref(1);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    shopName: undefined,
    packageableType: undefined,
    minimumPrice: undefined, // 最小价格
    maximumPrice: undefined // 最大价格
  },
  rules: {
    name: [
      {required: true, message: "名称不能为空", trigger: "blur"}
    ],
    mainPic: [
      {required: true, message: "主图不能为空", trigger: "blur"}
    ],
    price: [
      {required: true, message: "价格不能为空", trigger: "blur"}
    ],
    packagePrice: [
      {required: true, message: "套餐价格不能为空", trigger: "blur"},
      {
        validator: validateNowPrice,
        message: "套餐价格不能大于原价",
        trigger: 'blur'
      }
    ],
    personNum: [
      {required: true, message: "适用人数不能为空", trigger: "blur"}
    ],
    purchaseStartTime: [
      {required: true, message: "请选择活动报名时间", trigger: "blur"},
      {
        validator: validateSignTimeRange,
        trigger: 'change'
      }
    ],
    store: [
      {required: true, message: "不能为空", trigger: "blur"},
      {
        validator: (rule, value, callback) => {
          if (form.packageableType === 'Business'){
            callback();
          }
          if (value > editPersonNum.value) {
            if(editPersonNum.value>0) {
              callback(new Error("人数不能大于人数" + editPersonNum.value));
            }
            callback();
            
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ],
    purchaseNotes: [
      {required: true, message: "购买须知不能为空", trigger: "blur"}
    ],
    effectiveTime:[
      {required: true, message: "请选择有效期", trigger: "blur"}
    ]
  }
});

const {queryParams, form, rules} = toRefs(data);

function validateNowPrice(rule, value, callback) {
  if (route.query.packageableType === 'Play') {
    callback();
  }
  if (value >= form.value.price) {
    callback(new Error('套餐价格不能大于原价'));
  } else {
    callback();
  }
}

function validateSignTimeRange(rule, value, callback) {
  const purchaseEndTime = purchaseStartTimeRange.value ? purchaseStartTimeRange.value[1] : null;

  if(playType.value == 2) {
    if (purchaseEndTime && purchaseEndTime >playEndTime.value) {
      callback(new Error('报名结束时间不能大于活动结束时间:'+ playEndTime.value));
    } else {
      callback();
    }
  } else {
    if (purchaseEndTime && purchaseEndTime >playSignEnd.value) {
      callback(new Error('报名结束时间不能大于活动报名结束时间:'+ playSignEnd.value));
    } else {
      callback();
    }
  }
  
}

/** 查询团购套餐列表 */
function getList(id) {

  if (id !== null && typeof id !== 'object') {
    queryParams.value.packageableId = id;
    queryParams.value.packageableType = (route.query.packageableType != null) ? route.query.packageableType : queryParams.value.packageableType;
  }
  loading.value = true;
  if (route.query.playNum){
    playEndTime.value = route.query.playEndTime;
    playSignEnd.value = route.query.playSignEnd;
    playType.value = route.query.playType;
  }
  if (route.query.playNum && vueIndex.value === 1){
    personNum.value = route.query.playNum;
  }
  listPackage(queryParams.value).then(response => {
    packageList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    if (vueIndex.value === 1){
      for (let i = 0; i < packageList.value.length; i++) {
        personNum.value -= packageList.value[i].personNum;
      }
    }
    vueIndex.value += 1;
    console.log(personNum.value)
  });
}

// 取消按钮
function cancel() {
  //恢复人数
  editPersonNum.value = personNum.value
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: undefined,
    packageableId: route.params.id,
    name: undefined,
    mainPic: undefined,
    detailPic: undefined,
    price: undefined,
    packagePrice: undefined,
    effectiveTime: undefined,
    useTime: undefined,
    personNum: undefined,
    packageOrder: undefined,
    limitTimes: undefined,
    sold: undefined,
    store: undefined,
    desc: undefined,
    packageableType: route.query.packageableType,
    purchaseStartTime: undefined,
    purchaseEndTime: undefined,
    createTime: undefined,
    updateTime: undefined,
    isDisplay: undefined,
    purchaseNotes: undefined,
    serviceTime: undefined,
    reserveInfo: undefined
  };
  purchaseStartTimeRange.value = [];
  proxy.resetForm("packageRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList(route.params && route.params.id);
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value.maximumPrice = '';
  queryParams.value.minimumPrice = '';
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  let tablePersonNums = 0;
  ids.value = selection.map(item => item.id);
  selection.forEach(item => {
    tablePersonNums += item.personNum;
  });
  tablePersonNum.value = tablePersonNums;
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  editPersonNum.value =  personNum.value
  reset();
  open.value = true;
  title.value = "添加团购套餐";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  editPersonNum.value = personNum.value
  const _id = row.id || ids.value
  getPackage(_id).then(response => {
    form.value = response.data;
    purchaseStartTimeRange.value = [response.data.purchaseStartTime, response.data.purchaseEndTime];
    open.value = true;
    title.value = "修改团购套餐";
    //修改时恢复可以填写的活动人数
    editPersonNum.value += form.value.personNum;
  });
}

/** 提交按钮 */
function submitForm() {
  // console.log(111)
  proxy.$refs["packageRef"].validate(valid => {
    if (valid) {
      // form.value.personNum = form.value.store;
      if (form.value.id != null) {
        personNum.value = editPersonNum.value - form.value.personNum;
        updatePackage(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList(route.params && route.params.id);
        });
      } else {
        personNum.value = personNum.value - form.value.personNum;
        addPackage(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList(route.params && route.params.id);
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  let personNums  = 0;
  const _ids = row.id || ids.value;
  if (row.id){
    personNums = personNum.value + row.personNum;
  }else {
    personNums = tablePersonNum.value + personNum.value;
  }
  proxy.$modal.confirm('是否确认删除该数据项？').then(function () {
    return delPackage(_ids);
  }).then(() => {
    getList(route.params && route.params.id);
    personNum.value = personNums;
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/package/export', {
    ...queryParams.value
  }, `package_${new Date().getTime()}.xlsx`)
}

/** 详细按钮操作 */
function handleView(row) {
  const _id = row.id || ids.value
  fileList.value = [];
  getPackage(_id).then(response => {
    form.value = response.data;
    if (form.value.detailPic !== null && form.value.detailPic.includes(",")) {
      fileList.value = form.value.detailPic.split(",");
    }
    viewOpen.value = true;
  });
}

getList(route.params && route.params.id);

function handlePurchaseStartTimeRangeChange(value) {
  if (value && value.length === 2) {
    form.value.purchaseStartTime = value[0];
    form.value.purchaseEndTime = value[1];
  }
}

function handleEvaluation(row) {
  const id = row.id || ids.value[0];
  const packageableType = row.packageableType;
  router.push({
    path: "/shop/package/tyEvaluation/index/" + id,
    query: {pageNum: queryParams.value.pageNum, packageableType: packageableType}
  });
}

const stopWatching = watch(() => userStore.cascaderKey, (v) => {
  getList(route.params && route.params.id);
}, {immediate: true});

onBeforeUnmount(() => {
  stopWatching();
});
</script>
